package com.zx._02_thread.线程池;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * @version v1.0
 * @Project: knowledge
 * @Title: 任务提交执行排队到丢弃演示
 * @Description: TODO
 * @author: zhangxue
 * @date: 2020-7-2121:05:35
 * @company: zhangxue
 * @Copyright: Copyright (c) 2015
 */
@Slf4j
public class 任务提交执行排队到丢弃演示 {

    public static void main(String[] args) throws Exception {
        // 1. 比较普通的线程池使用，其中线程池满后，后面提交的任务被丢地
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 5, 60 * 60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.info("线程池已满，任务被淘汰");
            }
        });

        for (int i = 0; i < 100; i++) {
            final int idx = i;
            pool.execute(() -> {
                log.info("线程编号={}", idx);
                sleep(5);
//				sleep(60 * 60);
            });
            sleep(1);

            // 当前运行的任务数
            int activeCount = pool.getActiveCount();
            // 队列中的任务数
            int queueSize = pool.getQueue().size();
            // 全部的任务数
            long taskCount = pool.getTaskCount();
            // 全部完成的任务书
            long completedTaskCount = pool.getCompletedTaskCount();

            log.info("线程监控, activeCount={}, queueSize={}, taskCount={}, completedTaskCount={}", activeCount, queueSize,
                    taskCount, completedTaskCount);
        }
    }

    public static void sleep(long second) {
        try {
            TimeUnit.SECONDS.sleep(second);//一小时
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
